package com.showde.shoppingmall.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.kim.androidbase.imageloader.ImageLoader;
import com.showde.shoppingmall.R;
import com.showde.shoppingmall.business.logic.CallbackData;
import com.showde.shoppingmall.business.logic.ProductCollectionLogic;
import com.showde.shoppingmall.business.logic.ProductLogic;
import com.showde.shoppingmall.business.logic.UICallbackInterface;
import com.showde.shoppingmall.db.ProductCollectionDBCommand;
import com.showde.shoppingmall.db.ProductDBCommand;
import com.showde.shoppingmall.domain.Product;
import com.showde.shoppingmall.domain.ProductCollection;
import com.showde.shoppingmall.domain.SearchResult;
import com.showde.shoppingmall.utils.ToastUtils;

public class ProductCollectionAdapter extends BaseAdapter {

	private static final int MSG_DELETE_SUCCESS = 0x10001;
	private static final int MSG_DELETE_FAIL = 0x10002;

	private List<ProductCollection> productCollections;

	private Context context;

	private ImageLoader imageLoader;

	private ProductDBCommand productDBCommand;

	private ProductCollectionDBCommand collectionDBCommand;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_DELETE_SUCCESS:
				deleteSuccess();
				break;
			case MSG_DELETE_FAIL:
				deleteFail();
				break;
			}
			super.handleMessage(msg);
		}
	};

	public ProductCollectionAdapter(Context context,
			List<ProductCollection> productCollections) {
		this.context = context;
		this.productCollections = productCollections;
		imageLoader = new ImageLoader(context);
		productDBCommand = new ProductDBCommand(context);
		collectionDBCommand = new ProductCollectionDBCommand(context);
	}

	public void resetData(List<ProductCollection> productCollections) {
		this.productCollections = productCollections;
	}

	@Override
	public int getCount() {
		return productCollections.size();
	}

	@Override
	public ProductCollection getItem(int position) {
		return productCollections.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = LayoutInflater.from(context).inflate(
					R.layout.item_product_collection, null);
			holder = new ViewHolder();
			holder.title = (TextView) convertView
					.findViewById(R.id.txt_pro_desc);
			holder.logo = (ImageView) convertView
					.findViewById(R.id.img_product_icon);
			holder.delete = (ImageView) convertView
					.findViewById(R.id.img_delete);
			holder.time = (TextView) convertView.findViewById(R.id.txt_time);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		final ProductCollection productCollection = getItem(position);
		final String productId = productCollection.getProductId();
		if (productCollection.getProductTitle() == null) { // 需要获取商品简要信息

			final Product product = productDBCommand.query(productId);
			if (product == null || product.getProductID() == null) {
				ProductLogic.fetchProductSummary(context, productId,
						new UICallbackInterface() {

							@Override
							public void onSuccess(CallbackData data) {
								if (data != null) {
									List<SearchResult> searchResults = (List<SearchResult>) data.data;
									if (searchResults != null
											&& searchResults.size() > 0) {
										SearchResult result = searchResults
												.get(0);
										productCollection
												.setProductTitle(result.pDesc);
										productCollection
												.setProductLogo(result.pLogo);
										product.setProductID(productId);
										product.setProductName(result.pName);
										product.setProductTitle(result.pDesc);
										product.setProductLogo(result.pLogo);
										product.setProductPrice(Float
												.parseFloat(result.pPrice));
										productDBCommand.add(product);
										handler.post(new Runnable() {

											@Override
											public void run() {
												notifyDataSetChanged();
											}
										});
										data = null;
									}

								}

							}

							@Override
							public void onError(String errorMsg) {

							}
						});
				convertView.setVisibility(View.GONE);
				return convertView;
			} else {
				productCollection.setProductTitle(product.getProductTitle());
				productCollection.setProductLogo(product.getProductLogo());
			}
		}
		holder.title.setText(productCollection.getProductTitle());
		imageLoader.displayImage(productCollection.getProductLogo(),
				holder.logo);
		holder.time.setText("收藏时间:" + productCollection.getCollectiontime());
		holder.delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ProductCollectionLogic.deleteCollectedProduct(context,
						productId, new UICallbackInterface() {

							@Override
							public void onSuccess(CallbackData data) {

							}

							@Override
							public void onError(String errorMsg) {

							}
						});
			}
		});
		convertView.setVisibility(View.VISIBLE);
		return convertView;
	}

	private void deleteSuccess() {
		List<ProductCollection> collections = collectionDBCommand.queryAll();
		if (collections == null) {
			collections = new ArrayList<ProductCollection>();
		}
		this.productCollections = collections;
		notifyDataSetChanged();
	}

	private void deleteFail() {
		ToastUtils.showToast(context, "噢，删除失败了。。。");
	}

	private final class ViewHolder {
		TextView title;
		ImageView logo;
		TextView time;
		ImageView delete;
	}

}
